package com.kwamecorp.brunoperry.kwamelogo.engine;

import java.util.ArrayList;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;

public class KCGLSurfaceView extends GLSurfaceView
{
	public static String NAME = "KCGLSurfaceView";

	private Context context;
	private KCRenderer renderer;
	private boolean isRenderedCreated = false;
	private ArrayList<KCModel3D> models;
	private ArrayList<KCCamera3D> cameras;

	public KCGLSurfaceView(Context context) {
		super(context);

		this.context = context;

		if (checkES2(context))
		{
			init();
		}
	}
	
	public void addCamera(KCCamera3D cam)
	{
		renderer.addCamera(cam);
		cameras.add(cam);
		if(cameras.size() == 1)
		{
			float ratio = (float) getWidth() / getHeight();
			cam.init(ratio, -ratio, ratio, -1.0f, 1.0f, 1.0f, 2000.0f);
		}

	}

	public void addModel(KCModel3D model)
	{
		if (isRenderedCreated)
		{
			renderer.addModel(model);
		}
		models.add(model);
	}

	private void init()
	{
		setEGLContextClientVersion(2);

		models = new ArrayList<KCModel3D>();
		cameras = new ArrayList<KCCamera3D>();
		
		renderer = new KCRenderer(context);
		renderer.addOnSurfaceCreatedListener(new KCListener()
		{

			@Override
			public void onComplete()
			{
			}

			@Override
			public void onSurfaceCreated()
			{
				isRenderedCreated = true;
				if (models.size() == 1)
				{
					renderer.addModel(models.get(0));
				}
			}
		});
		setRenderer(renderer);
	}

	private boolean checkES2(Context context)
	{
		final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();

		return configurationInfo.reqGlEsVersion >= 0x20000;
	}
}
